import json
import random
from faker import Faker
from typing import List, Dict, Tuple
from tqdm import tqdm  # 进度条库
import os

# 初始化Faker
fake = Faker()  # 使用中文数据

# ------------------- 商品数据生成（保持原有逻辑）-------------------
# 商品类别和对应的属性模板
PRODUCT_CATEGORIES = {
    "ELECTRONIC": {
        "subcategories": ["PHONE", "LAPTOP", "TABLET", "SMARTWATCH", "HEADPHONE"],
        "brands": ["Apple", "Samsung", "Huawei", "Xiaomi", "Sony", "CHE"],
        #"features": ["高性能", "长续航", "高清屏幕", "防水", "无线充电"],
        #"purposes": ["办公", "娱乐", "学习", "游戏", "日常使用"]
    },
    "HOUSEHOLD": {
        "subcategories": ["SHEET SET", "KITCHEN SET", "CLEANING SET", "STORAGE SET", "DECORATION"],
        "brands": ["IKEA", "MUJI", "Haier", "Midea", "Lock&Lock", "CJM"],
        #"features": ["环保材料", "易清洁", "多功能", "便携", "耐用"],
        #"purposes": ["提升生活品质", "家居整理", "厨房烹饪", "卫生清洁", "装饰家居"]
    },
    "CLOTHING": {
        "subcategories": ["MENSWEAR", "WOMENSWEAR", "CHILDRENSWEAR", "SNEAKER", "ACCESSORIES"],
        "brands": ["Nike", "Adidas", "Uniqlo", "Zara", "H&M"],
        #"features": ["透气", "保暖", "时尚", "舒适", "防水"],
        #"purposes": ["日常穿着", "运动", "正式场合", "休闲", "防寒保暖"]
    }
}

def get_price_range(category):
    if category == "ELECTRONIC":
        price = round(random.uniform(3000, 15000), 2)
    elif category == "HOUSEHOLD":
        price = round(random.uniform(50, 2000), 2)
    else:
        price = round(random.uniform(100, 3000), 2)
    return price


def generate_products(num_products):
    """生成单个商品数据"""
    products = []

    for i in range(1, num_products + 1):
        category = random.choice(list(PRODUCT_CATEGORIES.keys()))
        subcategory = random.choice(PRODUCT_CATEGORIES[category]["subcategories"])
        brand = random.choice(PRODUCT_CATEGORIES[category]["brands"])

        # 生成商品名称
        name = f"{brand} {subcategory}"

        # 生成标签
        tags = [
            brand.lower(),
            subcategory.lower().replace(" ", "_")
        ]
        '''tags.extend(
            random.sample(
                [f.lower() for f in PRODUCT_CATEGORIES[category]["features"]],
                k=random.randint(1, 2)
            )
        )'''
        price = get_price_range(category)
        products.append({
            'id': i,
            'name': name,
            'category': category,
            'subcategory': subcategory,
            'tag':tags,
            'price': price
        })
    return products
    
    # 随机选择特征和用途
    # features = random.sample(PRODUCT_CATEGORIES[category]["features"], k=random.randint(2, 4))
    # purposes = random.sample(PRODUCT_CATEGORIES[category]["purposes"], k=random.randint(1, 3))
    
    # 生成商品描述
    # description = f"这款{subcategory}来自{brand}，具有{'、'.join(features)}等特点，适用于{'、'.join(purposes)}。"




fake = Faker('zh_CN')

# ------------------- 用户数据生成 -------------------
def generate_users(num_users, products):
    """生成用户数据"""
    users = []
    for user_id in range(1, num_users + 1):
        purchased_ids = [item['id'] for item in random.sample(products, random.randint(1, 5))]
        
        users.append({
            'user_name': f"user_{user_id}",
            #'user_name': fake.name(),
            'purchased_product_ids': purchased_ids
        })
    return users

# ------------------- 主逻辑 -------------------
def main():
    # 生成商品数据
    products= generate_products(1000)
    
    # 生成用户数据
    users = generate_users(66, products)
    
    # 保存数据
    with open("products.json", "w", encoding='utf-8') as f:
        json.dump(products, f, ensure_ascii=False, indent=2)
    
    with open("users.json", "w", encoding='utf-8') as f:
        json.dump(users, f, ensure_ascii=False, indent=2)
    
    print(f"生成完成！商品数据：products.json（{len(products)}条）")
    print(f"用户数据：users.json（{len(users)}条）")

if __name__ == "__main__":
    main()


print("\n文件保存路径：")
print(f"商品数据：{os.path.abspath('products.json')}")
print(f"用户数据：{os.path.abspath('users.json')}")